# import tesserocr  
from PIL import Image  
# import pyautogui
import numpy as np 
import cv2  
import time
from datetime import datetime
import pyautogui  


def match_photo(screenshot,template):
    # 检查图片是否成功加载  
    if screenshot is None or template is None:  
        print("Error loading images!")  
        return None
        
    res = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)  
    threshold = 0.85  # 匹配阈值  
    loc = np.where(res >= threshold)  
    
    # 由于可能有多个匹配点，我们只取匹配度最高的点  
    if len(loc[0]) > 0:  
        # 注意：loc[0] 和 loc[1] 分别包含 x 和 y 坐标  
        # 我们需要找到 res 数组中的最大值索引，但这里我们简单地取第一个匹配点  
        # 如果要找到最佳匹配，应该使用 np.unravel_index(np.argmax(res), res.shape)  
        top_left = loc[1][0], loc[0][0]  # 注意 PIL 和 OpenCV 的 y,x 顺序不同  
        bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0])  
    
        # 注意：我们不能直接在 screenshot_gray 上绘制矩形，因为它是 NumPy 数组  
        # 但我们可以打印匹配位置，或者将其转换回 PIL 图像并绘制矩形  
        # print(f"Match found at ({top_left[0]}, {top_left[1]})") 
        return top_left 
    else:  
        print("No match found.")
        return None

# def Identify_image(photo):
#     photo.convert('L')
#     # 创建PyTessBaseAPI实例  
#     with tesserocr.PyTessBaseAPI() as api:  
#         # 设置Tesseract的路径（通常不是必需的，因为tesserocr会自动找到它）  
#         # api.Init(r'D:\Program Files\Tesseract-OCR\', 'eng', tesserocr.OEM_LSTM_ONLY)  
#         api.SetVariable("tessedit_pageseg_mode", "4")  # PSM值为3 
#         # 设置字符白名单  
#         api.SetVariable("tessedit_char_whitelist", "0123456789")  
    
#         # 设置图像  
#         api.SetImage(photo)  
    
#         # 获取OCR结果  
#         text = api.GetUTF8Text()  
#         return text
        
            
def get_acerage_current():
    # 使用pyautogui捕获屏幕截图  
    screenshot = pyautogui.screenshot(region=(0, 0, 1920, 1080))  # 假设你的屏幕分辨率是1920x1080  
    # screenshot.save("./test.png")
    screenshot = np.array(screenshot.convert('L'))  # 将PIL图像转换为灰度NumPy数组

    # 读取模板图  
    template = cv2.imread('./zero_point.png', 0)  
    # template = cv2.imread('C:\\Users\\Administrator\\Desktop\\zero_point.png', 0)  
    
    coordinate = match_photo(screenshot,template)

    if coordinate is not None:
        left = int(coordinate[0])+125
        top = int(coordinate[1])+217
        width = 60  # 假设宽度是 60 像素  
        height = 15  # 假设高度是 20 像素  

        # 打开图片  
        # screenshot_mA = Image.open('C:\\Users\\Administrator\\Desktop\\2024-09-0409-23-56.png').convert('L')  # 转换为灰度图  
        screenshot_mA = pyautogui.screenshot(region=(left, top, width, height))  # 假设你的屏幕分辨率是1920x1080 
        back_up = screenshot_mA
        
        text = Identify_image(screenshot_mA)
        # 打印结果  
        # print(text)
        if(text!=''):
            return int(text)/100
        else:
            file_name = "./"
            now = datetime.now()  
            file_name += now.strftime("%Y-%m-%d%H-%M-%S")
            file_name += ".png"
            back_up.save(file_name)
            return None
# while True:
#     value = get_acerage_current()
#     # if value is None:
#     #     break
#     print(value)
#     time.sleep(0.5)
#template = Image.open('C:\\Users\\Administrator\\Desktop\\test33.png')  
#Identify_image(template)

def move_click(x,y):
    # 移动鼠标到屏幕坐标 (100, 100)  
    x = x+5
    y = y+5
    pyautogui.moveTo(x, y, duration=1)  # 1秒内移动到指定位置 
    # 在当前位置进行鼠标左键单击  
    pyautogui.click() 

start_point = int(input("请输入需要开始学习的行（不是序号）: "))
index = 0
file_path = 'D:\\study\\'
file_point = ''
index = start_point
playing_status = False
while True:
    time.sleep(2)
    if playing_status  is False:
        screenshot = pyautogui.screenshot(region=(960, 0, 1920, 1080))  # 假设你的屏幕分辨率是1920x1080  
        # screenshot.save(file_path+"screenshot.png")
        screenshot = np.array(screenshot.convert('L'))  # 将PIL图像转换为灰度NumPy数组

        # 读取模板图  
        # template = cv2.imread('./zero_point.png', 0)  
        template = cv2.imread(file_path+"dianbo.png", 0)
        coordinate = match_photo(screenshot,template)
        if coordinate is not None:
            move_click(coordinate[0] + 960 + 630,coordinate[1] + 68 + (index - 1)*31)
            time.sleep(15)
            move_click(960,542)
            time.sleep(2)
            pyautogui.scroll(-200)
            playing_status = True
    else :
        screenshot = pyautogui.screenshot(region=(500, 0, 1920, 1080))  # 假设你的屏幕分辨率是1920x1080  
        # screenshot.save("C:\\Users\\Administrator\\Desktop\\study\\screenshot.png")
        screenshot = np.array(screenshot.convert('L'))  # 将PIL图像转换为灰度NumPy数组
        template = cv2.imread(file_path+"queding.png", 0)  
        coordinate = match_photo(screenshot,template)
        if coordinate is not None:
            move_click(coordinate[0] + 500,coordinate[1])
            time.sleep(2)
            screenshot = pyautogui.screenshot(region=(960, 0, 1920, 1080))  # 假设你的屏幕分辨率是1920x1080  
            # screenshot.save("C:\\Users\\Administrator\\Desktop\\study\\screenshot.png")
            screenshot = np.array(screenshot.convert('L'))  # 将PIL图像转换为灰度NumPy数组
            template = cv2.imread(file_path+"guanbi.png", 0)  
            coordinate = match_photo(screenshot,template)
            if coordinate is not None:
                move_click(coordinate[0] + 960,coordinate[1])
                index = index + 1
                playing_status = False
    